package com.ywl.webserver.util;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * 
 * @author wl.yang
 *
 */
public class ConfigUtil {
	
	public static int port = 8888;
	public static String docBase = "";
	public static Map<String,ContextConfig> contextMap = new HashMap<String,ContextConfig>();

	public static void init(){
		File file = new File("config/server.xml");
		if(!file.exists()){
			throw new RuntimeException("server.xml not exists!");
		}
		
		SAXReader reader = new SAXReader(); 
		try {
			Document document = reader.read(file);
			Element rootElement = document.getRootElement();
			String portString = rootElement.attributeValue("port");
			docBase = rootElement.attributeValue("docBase");
			if(portString != null){
				port = Integer.parseInt(portString);
			}
			
			List<Element> elementList = rootElement.elements("Context");
			for(Element contextElement : elementList){
				String path = contextElement.attributeValue("path");
				String docBase = contextElement.attributeValue("docBase");
				ContextConfig contextConfig = new ContextConfig();
				contextConfig.setDocBase(docBase);
				contextConfig.setPath(path);
				contextMap.put(path, contextConfig);
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
	
//	public static void main(String[] args) {
//		ConfigUtil.init();
//		System.out.println(port);
//		System.out.println(contextMap);
//	}
}
